﻿using EnvCheck.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace EnvCheck.Utils
{
    public static class VersionCompareHelper
    {
        public static bool IsVersionMatch(string installedVersion, string expectedVersion, VersionMatchPolicy policy)
        {
            if (policy == VersionMatchPolicy.None)
                return true;

            if (string.IsNullOrEmpty(installedVersion) || string.IsNullOrEmpty(expectedVersion))
                return false;

            // 首先尝试完全相等
            if (string.Equals(installedVersion, expectedVersion, StringComparison.OrdinalIgnoreCase))
                return policy is VersionMatchPolicy.Equal or VersionMatchPolicy.GreaterThanOrEqual;

            // 解析成标准版本号
            if (Version.TryParse(installedVersion, out var vInstalled) && Version.TryParse(expectedVersion, out var vExpected))
            {
                int cmp = vInstalled.CompareTo(vExpected);
                return policy switch
                {
                    VersionMatchPolicy.Equal => cmp == 0,
                    VersionMatchPolicy.GreaterThan => cmp > 0,
                    VersionMatchPolicy.GreaterThanOrEqual => cmp >= 0,
                    _ => false,
                };
            }

            // 无法解析时，仅支持 Equal 策略（忽略大小写）
            return policy == VersionMatchPolicy.Equal &&
                   string.Equals(installedVersion, expectedVersion, StringComparison.OrdinalIgnoreCase);
        }


        public static void RegularizeAppName(
            ref string appName, string version)
        {
            appName = appName.Replace(version, "");
            //name = name.ToLower();
            appName = appName.Trim();
            // Replace this line:
            // if (name.EndsWith("-"))
            //     name = name[..^1].Trim();

            // With the following to fix CA1866:
            if (appName.EndsWith('-'))
                appName = appName[..^1].Trim();
            if( appName.EndsWith("()"))
                appName = appName[..^2].Trim();
        }
    }
}
